/******************************************************************
 * Created by: DO HOANG HAI                                       
 * Date of Creation: 8/Sep/2007     
 * Date of last modification: 13st/Sep/2007
 *                                                                
 * Description: Provide mean for adding item into the library.
 ******************************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Pbdms.BusinessLogic.DataController;
using Pbdms.Common.DataObject;


namespace Pbdms.Forms.Tools
{
    public partial class FrmAddItem : Form
    {
        
        public FrmAddItem()
        {
            InitializeComponent();
            //other initialization
            this.WindowState = FormWindowState.Normal;
            openFileDlg.FileOk += new CancelEventHandler(openFileDlg_FileOk);
            openFileDlgReviewFile.FileOk += new CancelEventHandler(openFileDlgReviewFile_FileOk);
            Pbdms.Common.Global.paintBackGround(this);
            loadCategories();
        }
        private void btnFileBrowser_Click(object sender, EventArgs e)
        {
            this.openFileDlg.ShowDialog();
            openFileDlg.Multiselect = false;                      
        }

        /// <summary>
        /// get the file name
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openFileDlg_FileOk(object sender, CancelEventArgs e)
        {
            try
            {
                tbFileLocation.Text = openFileDlg.FileName;
            }
            catch
            {
                Common.Global.showMsgOneButton("File Access is denied or other security authentication is required", 'W');
            }
        }
        private void openFileDlgReviewFile_FileOk(object sender, CancelEventArgs e)
        {
            try
            {
                tbReviewFile.Text = openFileDlgReviewFile.FileName;
            }
            catch
            {
                Common.Global.showMsgOneButton("File Access is denied or other security authentication is required", 'W');
            }
        }
        /// <summary>
        /// load categories from the database
        /// </summary>
        private void loadCategories()
        {
            ArrayList arl;
            arl = CategoryController.create().getListOfCategories();
            ddlCategory.Items.Clear();            
            for (int i = 0; i < arl.Count; i++)
            {
                ddlCategory.Items.Add(arl[i].ToString());
            }            
            ddlCategory.SelectedIndex = 0;            
        }

        /// <summary>
        /// cancel the action
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// add new item into database, together with comment, fileInfo data
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            ArrayList arlOfBibTexes = readBibTexes();
            //check if reading of bibTexes return a null (bibtexes may not be valid)
            if (arlOfBibTexes != null)
            {
                //item info
                Item itemObj = new Item("temp");
                itemObj.BibTexes = arlOfBibTexes;
                itemObj.BPrivate = !chkBShare.Checked;
                itemObj.Category = ddlCategory.SelectedText;

                //file info
                //temporarily assign an ID, this Id will be resolved later
                FileInfo fileInfoObj = new FileInfo("temp");
                //by default, existence is false, size is 0.0
                fileInfoObj.Existence = false;
                fileInfoObj.Size = 0;
                //document file
                String fileLocation = tbFileLocation.Text;

                if (!fileLocation.Equals(""))
                {
                    //if item's file is located on internet.
                    if (fileLocation.Contains("http"))
                    {
                        fileInfoObj.Location = fileLocation.Substring(0, fileLocation.LastIndexOf("/"));
                        fileInfoObj.FileName = fileLocation.Substring(fileLocation.LastIndexOf("/") + 1);                        
                        fileInfoObj.Existence = false;
                    }
                    else  //if item's file is located on local machine.
                    {
                        if (System.IO.File.Exists(fileLocation))
                        {
                            //if the file exists, store its information
                            fileInfoObj.Existence = true;

                            System.IO.FileInfo fInfo = new System.IO.FileInfo(fileLocation);
                            fileInfoObj.Location = fInfo.Directory.FullName;
                            fileInfoObj.FileName = fInfo.Name;
                            fileInfoObj.Size = fInfo.Length;

                            //check if need to copy the file to the folder
                            if (chkBCopy.Checked)
                            {
                                Pbdms.AppSetting aSetting = new AppSetting();
                                try
                                {
                                    Common.Global.copyFile(fileLocation, aSetting.LibFolder + "\\" + fileInfoObj.FileName);
                                    fileInfoObj.Location = aSetting.LibFolder;
                                }
                                catch
                                {
                                    Common.Global.showMsgOneButton("Unexpected Error, couldn't finish copying the file", 'I');
                                }
                            }
                        }                        
                    }                    
                }

                //comment info
                Comment commentObj = new Comment("temp");
                commentObj.Summary = tbSummary.Text;
                commentObj.Pros = tbPros.Text;
                commentObj.Cons = tbCons.Text;

                if (mtbRating.Text.Equals(" ."))
                    commentObj.Rating = 0.0;
                else
                    commentObj.Rating = Double.Parse(mtbRating.Text);
                //review file
                String reviewFile = tbReviewFile.Text;

                if (!reviewFile.Equals(""))
                {
                    //if item's file is located on internet.
                    if (fileLocation.Contains("http"))
                    {
                        commentObj.ReviewFile = reviewFile;
                    }
                    else  //if item's file is located on local machine.
                    {
                        Pbdms.AppSetting aSetting = new AppSetting();
                        try
                        {
                            Common.Global.copyFile(reviewFile, aSetting.LibFolder + "\\" + reviewFile.Substring(reviewFile.LastIndexOf("\\")+1));
                            commentObj.ReviewFile = aSetting.LibFolder + "\\" + reviewFile.Substring(reviewFile.LastIndexOf("\\") + 1);
                        }
                        catch
                        {
                            Common.Global.showMsgOneButton("Unexpected Error, couldn't finish copying the file", 'I');
                            commentObj.ReviewFile = "";
                        }
                    }
                }



                if (!tbTag.Text.Equals(""))
                {
                    ArrayList tags = new ArrayList();
                    String[] arrString = tbTag.Text.Trim().Split(',');
                    for (int i = 0; i < arrString.Length; i++)
                    {
                        tags.Add(arrString[i].ToString().Trim());
                    }
                    commentObj.Tags = tags;
                }

                //append new item into the database
                BusinessLogic.ItemSynchronizer.AppendNewItem(ref itemObj,ref commentObj,ref fileInfoObj);
                Common.Global.showMsgOneButton("The item has been added successfully to the library", 'I');
            }
        }

        /// <summary>
        /// read BibTexes from the form to an arraylist
        /// </summary>
        /// <returns></returns>
        private ArrayList readBibTexes()
        {
            ArrayList arlBibTexes = new ArrayList();
            String title = tbTitle.Text;
            String author = tbAuthor.Text;

            //check if all inputs are valid
            if (validate())
            {
                arlBibTexes.Add(new Common.DataObject.BibTexStruct("title", title));
                arlBibTexes.Add(new Common.DataObject.BibTexStruct("author", author));
                for (int i = 3; i <= 10; i++)
                {
                    //each bibtex value go along with a pair of dropdownlist and text box
                    ComboBox ddl = (ComboBox)(this.Controls.Find("ddl" + i, true)[0]);
                    TextBox tb = (TextBox)(this.Controls.Find("tb" + i, true)[0]);
                    //check to see this pair of ddl and tb provide valid input, if not -> ignore 
                    if (validateBib(ddl, tb))
                    {                        
                        arlBibTexes.Add(new Common.DataObject.BibTexStruct(ddl.SelectedItem.ToString().ToLower(), tb.Text.Trim()));
                    }
                }
                return arlBibTexes;
            }
            else
                return null;
        }
        /// <summary>
        /// check to see if author or title is missing
        /// </summary>
        /// <returns></returns>
        private bool validate()
        {
            String title = tbTitle.Text;
            String author = tbAuthor.Text;

            if (title.Equals("") || author.Equals(""))
            {
                Common.Global.showMsgOneButton("Title and Author are required!", 'W');
                if (title.Equals(""))
                    tbTitle.Focus();
                else
                    tbAuthor.Focus();
                return false;
            }
            else
                return true;
        }

        /// <summary>
        /// validate a pair of dropdownlist and text box provide valid bibTex
        /// </summary>
        /// <param name="ddl"></param>
        /// <param name="tb"></param>
        /// <returns></returns>
        private bool validateBib(ComboBox ddl, TextBox tb)
        {            
            if (ddl.SelectedItem == null )
            {
                if (!tb.Text.Equals(""))
                {
                    Common.Global.showMsgOneButton("Please specify the attribute's name", 'I');
                    ddl.Focus();
                }
                return false;
            }
            else 
            {
                if (tb.Text.Equals(""))
                    return false;
                else return true;
            }
           
        }

        private void mtbRating_TextChanged(object sender, EventArgs e)
        {
            string newRatingValue = normalizeMtbRating(mtbRating.Text);
            if (! newRatingValue.Equals("0.0") && Double.Parse(newRatingValue) > 5)
            {
                Common.Global.showMsgOneButton("Invalid value! Rating must be in between 0 and 5", 'W');
                mtbRating.ResetText();
            }            
        }

        /// <summary>
        /// normalize the text in the masked text box for rating of item to be in friendly number format
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        private String normalizeMtbRating(String s)
        {
            String[] ar = s.Split('.');
            String sReturn = "";
            if (ar[0].Equals(" "))
                sReturn = "0";
            else
                sReturn = ar[0];

            if (!ar[1].Equals(""))
                sReturn += "." + ar[1];
            return sReturn;
        }

        private void btnReviewFileBrowser_Click(object sender, EventArgs e)
        {
            this.openFileDlgReviewFile.ShowDialog();
            openFileDlgReviewFile.Multiselect = false;
        }

        
    }
}